package com.horizon.ContentProvider;

import java.util.HashMap;

import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

public class MyContentProvider extends ContentProvider {


	// private static final String TAG = "MyContentProvider";
 
    private static final String MY_DATABASE_NAME = "horizonData.db";
 
    private static final int MY_DATABASE_VERSION = 1;
 
    private static final String MY_TABLE_NAME = "data";
 
    public static final String AUTHORITY = "com.horizon.ContentProvider.MyContentProvider.mohsen";
 
    
    private static final int DATAID = 1;
    private static final int DATAIDs = 2;
				 
    public static final String CONTENT_ID = "_id";
    public static final String NAME = "name";
    public static final String PWD = "pwd";
    public static final String PHONE = "phone";
    public static final String EMAIL = "email";
    public static final String COL_URL = "url";
	
    private static final String CREATE_TABLE_TUTORIALS = "create table " + MY_TABLE_NAME
    		+ " (" + CONTENT_ID + " integer primary key autoincrement, " +
    		NAME + " text not null," + 
			PWD + " text not null," + 
			PHONE+ " text not null," + EMAIL+ " text not null," + COL_URL + " text not null )";
			
    private static final String DB_SCHEMA = CREATE_TABLE_TUTORIALS;
	
 //   private static final String AUTHORITY = "com.mamlambo.tutorial.tutlist.data.TutListProvider";
  //  public static final int TUTORIALS = 100;
  //  public static final int TUTORIAL_ID = 110;
     
    private static final String TUTORIALS_BASE_PATH = "data";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
            + "/" + TUTORIALS_BASE_PATH);
     
    public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
            + "/mt-data";
    public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
            + "/mt-data";
    
//	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/data");		
//	private static final String CONTENT_TYPE = AUTHORITY + "/" + MY_TABLE_NAME;
	
	private static HashMap<String, String> myProjectionMap;
	
	private static final UriMatcher mURIMatcher = new UriMatcher(
	        UriMatcher.NO_MATCH);
	static {
	    mURIMatcher.addURI(AUTHORITY, TUTORIALS_BASE_PATH, DATAID);
	    mURIMatcher.addURI(AUTHORITY, TUTORIALS_BASE_PATH + "/#", DATAIDs);

	    myProjectionMap = new HashMap<String, String>();
		myProjectionMap.put(CONTENT_ID, CONTENT_ID );
		myProjectionMap.put(NAME,NAME );
		myProjectionMap.put(PWD,PWD );
		myProjectionMap.put(PHONE, PHONE);
		myProjectionMap.put(EMAIL,EMAIL );
		myProjectionMap.put(COL_URL,COL_URL);
 	 
	}
	 
	//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	private static class DataBaseHelper extends SQLiteOpenHelper{

		public DataBaseHelper(Context context){
			super(context,MY_DATABASE_NAME, null, MY_DATABASE_VERSION);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL(DB_SCHEMA);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			
		}
		
	}
	private DataBaseHelper dbHelper;
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	
	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		Log.d("Mohsen", "MyContentProvider: onCreate");
		dbHelper = new DataBaseHelper(getContext());
		return true;
	}
	
	@Override
	public Uri insert(Uri uri, ContentValues cv) {
		// TODO Auto-generated method stub
		Log.d("Mohsen", "MyContentProvider: insert");
		if(mURIMatcher.match(uri) == DATAID){
			Log.d("Mohsen", "MyContentProvider: insert: uri matched");
			long nrow=0;
			ContentValues tcv;
			if(cv == null){
				tcv = new ContentValues();
			}
			else{
				tcv = new ContentValues(cv);
			}
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			nrow = db.insert(MY_TABLE_NAME, CONTENT_ID , tcv);
			if(nrow > 0){
				Uri turi = ContentUris.withAppendedId(CONTENT_URI, nrow);
				Log.d("Mohsen", "MyContentProvider: insert: NewUri=" + turi.toString());
				getContext().getContentResolver().notifyChange(turi, null);
				return turi;
			}
		}
		else{
			throw new IllegalArgumentException("URI not matched!");
		}
		throw new SQLException("Failed to insert row into " + uri);
	}
	
	@Override
	public int delete(Uri uri, String sel, String[] selArg) {
		// TODO Auto-generated method stub
		if(mURIMatcher.match(uri) == DATAID){
			int nrow=0;
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			nrow = db.delete(MY_TABLE_NAME, sel, selArg);
			if(nrow > 0){
				Uri turi = ContentUris.withAppendedId(CONTENT_URI, nrow);
				getContext().getContentResolver().notifyChange(turi, null);
				return nrow;
			}
		}
		else{
			throw new IllegalArgumentException("URI not matched!");
		}
		throw new SQLException("Failed to delete from"+ uri);
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		if(mURIMatcher.match(uri) == DATAID){
			return CONTENT_TYPE;
		}
		else{
			throw new IllegalArgumentException("URI not matched!");
		}
	}

	

	@Override
	public Cursor query(Uri uri, String[] proj, String sel, String[] selArg,
			String sortOrder) {
		// TODO Auto-generated method stub
		Log.d("Mohsen", "MyContentProvider: query: ");
	    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
	    queryBuilder.setTables(MY_TABLE_NAME);
	 
	    int uriType = mURIMatcher.match(uri);
	    switch (uriType) {
	    case DATAID:
	        queryBuilder.setProjectionMap(myProjectionMap);
	        break;
	    case DATAIDs:
	    	queryBuilder.appendWhere(CONTENT_ID + "="
	                + uri.getLastPathSegment());
	        // no filter
	        break;
	    default:
	        throw new IllegalArgumentException("Unknown URI");
	    }
	 
	    Cursor cursor = queryBuilder.query(dbHelper.getReadableDatabase(),
	            proj, sel, selArg, null, null, sortOrder);
	    cursor.setNotificationUri(getContext().getContentResolver(), uri);
	    return cursor;
	}

	@Override
	public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
		// TODO Auto-generated method stub
		return 0;
	}


}
